<template>
  <el-container>
    <el-main class="leftMain">
      <device-tree
        :show-tabs="false"
        :show-device-index="false"
        :query-data="queryData"
        :first-action="false"
      ></device-tree>
    </el-main>
    <el-main class="rightMain">
      <bs-main>
        <device-monitor-condition
          slot="header"
          :query-data="queryData"
          :state-btn-disabled="setStateBtn"
          :export-data="exportData"
        ></device-monitor-condition>
      <list
          ref="list"
          class="center"
          height="calc(100vh - 220px)"
          :table-tag="tableName"
          :list-data="tableData"
          :has-select="true"
          :list-cols="colData"
          :init-cols-props.sync="initColsProps"
          :init-headmune-flag="initHeadmuneFlag"
          :action-opts="actionOpts"
          @sort="handleSort"
          @init-table="initTable"
          @selection-change="handleSelectionChange"
        >
          <template slot="onlineSlot" slot-scope="{ row }">
            {{ row.online | onlineFilter(te) }}
          </template>
        </list>
        <pagination
          slot="footer"
          :total="pageData.total"
          :page="pageData.page"
          :limit="pageData.limit"
          :showAllChecked="true"
          :allChecked="queryData.allSize"
          @pagination="doList"
          @all="handleChangeAllSize"
        ></pagination>
      </bs-main>
      <edit-device-dialog></edit-device-dialog>
      <device-info-dialog></device-info-dialog>
      <SyslogCommandDialog :visible.sync="showSyslogCommandDialog" @send="handelSendSyslogCommond"></SyslogCommandDialog>
    </el-main>
  </el-container>
</template>


<script>
import Pagination from '@/components/Pagination'
import DeviceTree from '../components/DeviceTree'
import DeviceMonitorCondition from './components/DeviceMonitorCondition'
import List from '@/components/List'
import EditDeviceDialog from '../device-info/components/EditDeviceDialog'
import DeviceInfoDialog from './components/State/DeviceInfoDialog'
import SyslogCommandDialog from './components/SyslogCommandDialog'
import DeviceMonitorApi from '@/api/device'

export default {
  data() {
    const headerContextMenus = {
      width: '120px',
      items: ['sortUp', 'sortDown', 'line', 'cols'],
    }
    return {
      showContextMenu: false,
      queryData: { queryType:0, allSize: false },
      loading: null,
      tableData: [],
      actionOpts: {
        show: false,
      },
      colData: [
        { label: '名称', prop: 'name', width: '125px',minwidth: '125', headerContextMenus },
        {
          label: 'MAC地址',
          prop: 'macText',
          minwidth: '125',
          headerContextMenus,
        },
        {
          label: '状态',
          prop: 'online',
          minwidth: '70',
          headerContextMenus,
          slot: true,
        },
        { label: '终端IP', prop: 'connectIp', minwidth: '110', headerContextMenus },
        {
          label: '软件版本',
          prop: 'swVersion',
          minwidth: '100',
          headerContextMenus,
        },
         {
          label: '最后上线时间',
          prop: 'lastOnlineTime',
          minwidth: '120',
          headerContextMenus,
        },
        {
          label: '4G信号',
          prop: 'simSignal',
          minwidth: '90',
          headerContextMenus,
        },


        {
          label: '当前SIM串号',
          prop: 'simIccid',
          minwidth: '120',
        },
        {
          label: '最后心跳时间',
          prop: 'lastHeartTime',
          minwidth: '120',
          headerContextMenus,
        },
        {
          label: '在线时间',
          prop: 'onlineTime',
          minwidth: '100',
          headerContextMenus,
        },
        {
          label: '当前节目',
          prop: 'program',
          minwidth: '100',
          headerContextMenus,
        },
        {
          label: '下载率',
          prop: 'programDownPercent',
          minwidth: '80',
          headerContextMenus,
        },
      ],
      initColsProps: [
        'name',
        'macText',
        'connectIp',
        'simSignal',
        'swVersion',
        'online',
        'lastOnlineTime',
        'simIccid',
        'lastHeartTime',
        'onlineTime',
        'program',
        'programDownPercent',
      ],
      dropdownList: [
        { visible: false, value: '1', label: '升序' },
        { visible: false, value: '2', label: '降序' },
      ],
      pageData: {
        page: 1,
        total: 0,
        limit: 15,
      },
      macs: [],
      terminalIds: [],
      tableName:'deviceMonitorTable',
      initHeadmuneFlag: false,
      showSyslogCommandDialog: false,
      headerList: [],
      propList: [],
      exportData:[],
    }
  },
  mounted: function () {
    this.$nextTick(function () {
      this.doList()
    })
  },
  created() {
    this.$eventBus.$on('doStateInfo', this.doStateInfo)
    this.$eventBus.$on('doSet', this.doSet)
    this.$eventBus.$on('doList', this.doList)
    this.$eventBus.$on('doChangeOrder', this.doChangeOrder)
    this.$eventBus.$on('doCancelAllSize', this.doCancelAllSize)
  },
  beforeDestroy() {
    this.$eventBus.$off('doStateInfo')
    this.$eventBus.$off('doSet')
    this.$eventBus.$off('doList')
    this.$eventBus.$off('doChangeOrder')
    this.$eventBus.$off('doCancelAllSize')
  },
  computed: {
    setStateBtn() {
      if (this.queryData.allSize || this.terminalIds.length > 1) {
        return true
      } else {
        return false
      }
    },
  },
  filters: {
    onlineFilter(val,te) {
      if (val == 1) {
        return te('在线')
      } else if(val == 2) {
        return te('待机')
      } else {
        return te('离线')
      }
    },
  },
  methods: {
    initTable(config){
      this.initHeadmuneFlag = true
    },
    // 查询列表
    async doList(current) {
      if (current) {
        this.pageData = {
          ...this.pageData,
          ...current,
        }
      }
      this.queryData.allSize = false
      var queryData = this.$data.queryData
      queryData.current = this.pageData.page
      queryData.size = this.pageData.limit
      queryData.showChild = true
      const res = await DeviceMonitorApi.deviceMonitorList(queryData)
      if (res) {
        this.tableData = res.records ? res.records: []
        this.pageData.total = Number(res.total? res.total: 0)
      }
    },

    // 多选
    handleSelectionChange(val) {
      this.macs = []
      this.terminalIds = []
      this.exportData = []
      for (let i = 0; i < val.length; i++) {
        this.macs.push(val[i].macText)
        this.terminalIds.push(val[i].terminalId)
      }
       this.tableData.forEach(element => {
          this.terminalIds.forEach(id => {
            if(id == element.terminalId)
            {
              this.exportData.push(element)
            }
          });
        });
    },
    // 设置
    async doSet() {
      if (!this.queryData.allSize && this.macs.length < 1) {
        this.$alert('提示', '请先选择终端')
        return
      }
      if (this.macs.length === 1) {
        const res = await DeviceMonitorApi.getDeviceBy({ id: this.terminalIds[0] })
        if (res) {
          this.$eventBus.$emit('addDeviceDialogShow', res)
        }
      } else {
        let queryData = {}
        if(this.queryData.allSize) {
          queryData = {
            ...this.queryData,
            queryGroupId: this.queryData.groupId,
            type: 2
          }
          delete queryData.groupId
        }
        this.$eventBus.$emit('addDeviceDialogShow', { macs: this.macs, ids: this.terminalIds}, queryData)
      }
    },
    async doStateInfo(row) {
      if (row) {
        const res = await DeviceMonitorApi.getDeviceMonitorBy({
          terminalId: row.terminalId,
        })
        this.$eventBus.$emit('deviceInfoDialogShow', res, row.terminalId)
      } else {
        if (this.terminalIds.length < 1) {
          this.$alert('提示', '请先选择终端')
          return
        }
        const terminalId = this.terminalIds[0]
        const res = await DeviceMonitorApi.getDeviceMonitorBy({
          terminalId: terminalId,
        })
        this.$eventBus.$emit('deviceInfoDialogShow', res, terminalId)
      }
    },
    // 终端命令
    async doChangeOrder(data) {
      if(!this.queryData.allSize) {
        if (this.terminalIds.length < 1) {
          this.$alert('提示', '请先选择终端')
          return
        }
      }
      const _this = this
      switch (data) {
        case 'kj':
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }
          var res = await DeviceMonitorApi.commandSwitch({
            terminalIds: this.terminalIds,
            power:1,
            ...this.queryData
          }).finally(function () {
            if (_this.loading) {
              _this.loading.close()
              _this.loading = null
            }
          })
          this.doCancelAllSize();
          this.$alert(
            '提示',
            'sendPromptOfOpen'
          )
          break
        case 'cq':
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }

          res = await DeviceMonitorApi.commandSwitch({
            terminalIds: this.terminalIds,
            power:2,
            ...this.queryData
          }).finally(function () {
            if (_this.loading) {
              _this.loading.close()
              _this.loading = null
            }
          })
          this.doCancelAllSize();
          this.$alert(
            '提示',
            'sendPromptOfReboot'
          )
          break
        case 'dj':
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }
          res = await DeviceMonitorApi.commandSwitch({
            terminalIds: this.terminalIds,
            power:0,
            ...this.queryData
          }).finally(function () {
            if (_this.loading) {
              _this.loading.close()
              _this.loading = null
            }
          })
          this.doCancelAllSize();
          this.$alert(
            '提示',
            'sendPromptOfWait'
          )
          break
        case 'dzwldj':
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }
          res = await DeviceMonitorApi.commandMapSwitch({
            terminalIds: this.terminalIds,
            ...this.queryData
          }).finally(function () {
            if (_this.loading) {
              _this.loading.close()
              _this.loading = null
            }
          });
          this.doCancelAllSize();
          this.$alert(
            '提示',
            'sendMapPromptOfWait'
          )
          break
        case 'ql':
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }
          res = await DeviceMonitorApi.commandClearFile({
            terminalIds: this.terminalIds,
            ...this.queryData
          }).finally(function () {
            if (_this.loading) {
              _this.loading.close()
              _this.loading = null
            }
          })
          this.doCancelAllSize();
          this.$alert(
            '提示',
            'sendPromptOfClean'
          )
          break
        case 'jd':
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }
          res = await DeviceMonitorApi.commandClock({
            terminalIds: this.terminalIds,
            ...this.queryData
          }).finally(function () {
            if (_this.loading) {
              _this.loading.close()
              _this.loading = null
            }
          })
          this.doCancelAllSize();
          this.$alert(
            '提示',
            'sendPromptOfNetworkTime'
          )
          break
        case 'sj':
          this.$eventBus.$emit('showTerminalUpgradeDialog',this.terminalIds, this.queryData)
          break
        case 'scxt':
          this.showSyslogCommandDialog = true
          break
        case 'scbf':
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }
          res = await DeviceMonitorApi.commandUploadPlayLog({
            terminalIds: this.terminalIds,
            ...this.queryData
          }).finally(function () {
            if (_this.loading) {
              _this.loading.close()
              _this.loading = null
            }
          })
          this.doCancelAllSize();
          this.$alert(
            '提示',
            'sendPromptOfUploadPlayFile'
          )
          break
        case 'cb':
          this.$eventBus.$emit('showInsertTextDialog',this.terminalIds, this.queryData)
          break
        case 'kqdtmb':
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }
          res = await DeviceMonitorApi.commandOparetinDTMB({
            terminalIds: this.terminalIds,
            enable:true,
            ...this.queryData
          }).finally(function () {
            if (_this.loading) {
              _this.loading.close()
              _this.loading = null
            }
          })
          this.doCancelAllSize();
          this.$alert(
            '提示',
            'sendPromptOfOpenDTMB'
          )
          break
        case 'gbdtmb':
          if (this.loading === null) {
            this.loading = this.$loading({
              fullscreen: true,
              text: '正在发送终端命令',
            })
          }
          res = await DeviceMonitorApi.commandOparetinDTMB({
            terminalIds: this.terminalIds,
            enable:false,
            ...this.queryData
          }).finally(function () {
            if (_this.loading) {
              _this.loading.close()
              _this.loading = null
            }
          })
          this.doCancelAllSize();
          this.$alert(
            '提示',
            'sendPromptOfCloseDTMB'
          )
          break
      }
    },
    // 发送系统日志命令
    async handelSendSyslogCommond(formdata) {
      this.loading = this.$loading({
        fullscreen: true,
        text: '正在发送终端命令',
      })
      const _this = this
      await DeviceMonitorApi.commandUploadSysLog({
        terminalIds: this.terminalIds,
        ...this.queryData,
        ...formdata
      }).finally(function () {
        if (_this.loading) {
          _this.loading.close()
          _this.loading = null
        }
      })
      this.doCancelAllSize();
      this.showSyslogCommandDialog = false
      this.$alert(
        '提示',
        'sendPromptOfUploadSystemFile'
      )
    },
    // 排序
    handleSort(sortInfo) {
      switch (sortInfo.prop) {
        case 'name':
          this.queryData.orderType = 1
          break
        case 'macText':
          this.queryData.orderType = 2
          break
        case 'lanIp':
          this.queryData.orderType = 3
          break
        case 'simSignal':
          this.queryData.orderType = 7
          break
        case 'dtmbSignal':
          this.queryData.orderType = 8
          break
        case 'model':
          this.queryData.orderType = 9
          break
        case 'swVersion':
          this.queryData.orderType = 10
          break
        case 'online':
          this.queryData.orderType = 11
          break
        case 'lastOnlineTime':
          this.queryData.orderType = 12
          break
        case 'lastHeartTime':
          this.queryData.orderType = 13
          break
        case 'onlineTime':
          this.queryData.orderType = 14
          break
        case 'program':
          this.queryData.orderType = 15
          break
        case 'programDownPercent':
          this.queryData.orderType = 16
          break
        default:
          this.$alert('提示', '系统不支持排序')
          return
      }
      this.queryData.orderParam = sortInfo.type
      this.doList()
    },

    // 选择所有页
    handleChangeAllSize(val) {
      this.$set(this.queryData, 'allSize', val)
      this.$set(this.queryData, 'total', this.pageData.total)
      this.$refs.list.clearSelection();
    },
    doCancelAllSize() {
      this.$set(this.queryData, 'allSize', false)
    },
    te(arg) {
      const hasKey = this.$te(arg)
      if (hasKey) {
        const result = this.$t(arg)
        return result
      }
      return arg
    },
  },
  components: {
    DeviceTree,
    DeviceMonitorCondition,
    List,
    EditDeviceDialog,
    DeviceInfoDialog,
    Pagination,
    SyslogCommandDialog
  },
}
</script>

<style lang="scss" scoped>
.leftMain {
  // ::v-deep .el-tree>.el-tree-node {
  //   min-width:100%;
  //   height: calc(100vh - 163px);
  //   display:inline-block;
  // }
  // ::v-deep .tree{width: 100%; height: 100%; overflow-x: scroll;
  // // scrollbar-width: thin;
  // }
  ::v-deep .el-tree-node {
      position: relative;
      padding-left: 10px;
  }
}
</style>
